<template>
  <div class="asideTable">
    <div class="all" ref="leftRef">
      <div class="alltitle">全部功能模块</div>
      <div class="tree_div">
        <el-tree
          @check="check"
          ref="tree"
          :data="processedParentMenus"
          show-checkbox
          node-key="menuId"
          :props="props"
          @node-click="handleNodeClick"
          @node-expand="changeWidth"
          @node-collapse="changeWidth"
        ></el-tree>
      </div>
    </div>
    <div class="table_module">
      <el-table
        id="elTable"
        ref="table"
        :data="rightDataList"
        height="100%"
        highlight-current-row
        @row-contextmenu="rowRightClick"
        @header-contextmenu="headerRightClick"
      >
        <el-table-column
          v-for="(item, index) in buttons"
          :key="index"
          prop="name"
          :label="item.description"
          :width="index == 0 ? 148 : 60"
        >
          <!-- <template slot-scope="scope"  slot="header">
          <el-checkbox ></el-checkbox>{{ scope.row.name }}
          </template>-->
          <template #header>
            <div :key="index">{{ item.description }}</div>
            <!-- <div v-else>
              <el-checkbox
                :indeterminate="item.indeterminate"
                v-model="item.selected"
                :key="item.description"
                @change="changeColumnChecked(index, item.selected)"
                >{{ item.description }}</el-checkbox
              >
              {{ item.description }}
            </div>-->
          </template>
          <template slot-scope="scope">
            <div
              style="width: 100%; display: flex; justify-content: flex-start"
              v-if="index == 0"
              :key="scope.row.description"
            >
              <el-checkbox
                :disabled="isAdmin"
                v-model="scope.row.selected"
                style="padding-right: 2px"
                @change="changeAllCheckBox(scope.row, scope.row)"
              >{{ scope.row.description }}</el-checkbox>
            </div>
            <!--
              v-model="scope.row.buttons[index].checked"
            @change="test(scope.row)"-->
            <div v-else-if="scope.row.permissions[index - 1]" :key="index - 1">
              <el-checkbox
                :disabled="isAdmin"
                v-model="scope.row.permissions[index - 1].selected"
                @change="changeSingleCheckBox(scope.row, scope.row.permissions[index - 1])"
              ></el-checkbox>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getAction, postAction } from '@/api/manage'
let index = 0
export default {
  props: {
    dataTree: {
      type: Object,
      default: {},
      require: false,
    },
    isAdmin: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    processedParentMenus() {
      const setDisable = (nodes) => {
        return nodes.map(node => ({
          ...node,
          disabled: this.isAdmin,
          children: node.children ? setDisable(node.children) : []
        }))
      }
      return setDisable(this.parentMenus)
    }
  },
  data () {
    return {
      table: '业务处理',
      props: {
        label: 'name',
        children: 'children',
      },
      checkedTest: true,
      dataList: [],
      // 右侧子菜单及权限
      rightDataList: [],
      buttons: [],
      childFunctionHasOptionsList: [],
      newCheckIds: [],
      leftCheckData: {},
      checked: false,
      borther: [],
      resources: [],
      parentMenus: [],
      childMenus: [],
      // 所有菜单及权限
      menuList: [],
      roleId: '',
      roleCode: ''
    }
  },
  mounted () {
    document.getElementById('elTable').oncontextmenu = function (params) {
      return false;
    }
  },
  // watch: {
  // dataTree(val) {
  //   this.roleId = val.roleId
  //   this.menuList = val.menuList
  //   this.parentMenus = val.parentMenus
  //   let checkedIds = []
  //   this.parentMenus.forEach((el) => {
  //     if (el.selected) {
  //       checkedIds.push(el.menuId)
  //     }
  //   })
  //   this.loadTreeCheckedByCheckId(checkedIds)
  //   this.loadMenuPermissions(this.parentMenus[0].menuId)
  // },
  // },
  methods: {
    edit (item) {
      this.roleId = item.roleId
      this.roleCode = item.roleCode
      this.menuList = item.menuList
      this.parentMenus = item.parentMenus
      let checkedIds = []
      this.parentMenus.forEach((el) => {
        if (el.selected) {
          checkedIds.push(el.menuId)
        }
      })
      this.loadTreeCheckedByCheckId(checkedIds)
      this.loadMenuPermissions(this.parentMenus[0].menuId)
    },
    // 获取菜单权限
    loadMenuPermissions (menuId) {
      // 更换主菜单时, 把修改的结果进行保存
      this.rightDataList.forEach((right) => {
        this.menuList.forEach((menu) => {
          if (right.menuId == menu.menuId) {
            menu = right
          }
        })
      })
      // 重置右侧功能模块信息
      this.rightDataList = []
      this.menuList.forEach((res) => {
        if (res.parentId == menuId) {
          this.rightDataList.push(res)
        }
      })
      // ; (this.buttons = [{ description: '功能模块' }]),
      //   this.rightDataList[0].permissions.forEach((el) => {
      //     this.buttons.push(el)
      //   })
      if (this.rightDataList && this.rightDataList.length > 0) {
        this.buttons = [{ description: '功能模块' }]
        let perm = this.rightDataList[0].permissions || []
        if (perm && perm.length > 0) {
          perm.forEach((el) => {
            this.buttons.push(el)
          })
        }
      }
    },

    // 改变宽度
    changeWidth () {
      let wi = getComputedStyle(this.$refs.leftRef).width
    },
    check (data, value) {
      // 保存 主菜单选中状态
      this.parentMenus.forEach((el) => {
        el.selected = false
      })
      if (value.checkedKeys.length == 0) {
      } else {
        value.checkedNodes.forEach((cm) => {
          cm.selected = true
          this.parentMenus.forEach(el => {
            if (el.menuId == cm.menuId) {
              el = cm
            }
          })
        })
      }
      // 更新 所有菜单选中状态
      this.parentMenus.forEach((pm) => {
        this.menuList.forEach((el) => {
          if (el.menuId == pm.menuId) {
            el = pm
          }
        })
      })
    },
    // 节点被点击，或勾选以及勾选取消时
    handleNodeClick (data) {
      this.loadMenuPermissions(data.menuId)
    },
    //加载左侧树选中状态
    loadTreeCheckedByCheckId (ids) {
      this.$refs.tree.setCheckedKeys(ids)
    },
    //加载右侧头部资源选中状态
    loadRightHeadChecked () {
      //从索引为1开始，排除功能模块
      for (let i = 1; i < this.buttons.length; i++) {
        let allChecked = []
        for (let item of this.resources) {
          if (item.buttons[i].hasOption) {
            //存在按钮则记录状态，不存在则不记录
            allChecked.push(item.buttons[i].checked)
          }
        }
        //半选状态
        if (allChecked.indexOf(true) > -1 && allChecked.indexOf(false) > -1) {
          this.buttons[i].checked = false
          this.buttons[i].indeterminate = true
        } else if (allChecked.indexOf(true) > -1 && allChecked.indexOf(false) < 0) {
          //全选
          this.buttons[i].checked = true
          this.buttons[i].indeterminate = false
        } else {
          //全不选
          this.buttons[i].checked = false
          this.buttons[i].indeterminate = false
        }
      }
    },
    //获取data的兄弟节点
    getBrotherNodes (data, list) {
      for (let i = 0; i < list.length; i++) {
        const el = list[i]
        if (el.superiorId == data.superiorId) {
          // this.rightDataList.push(el)
          this.borther.push(el)
        } else {
          if (el.children) {
            this.getBrotherNodes(data, el.children)
          }
        }
      }
    },
    addProperty () {
      for (let item of this.resources) {
        this.rightDataList.push(item)
      }
    },
    //右侧功能 所有功能状态改变
    changeAllCheckBox (row, node) {
      node.permissions.forEach((el) => {
        el.selected = node.selected
      })
    },
    //右侧功能 单个节点改变
    changeSingleCheckBox (row, node) {
      if (!node.selected) {
        row.selected = false
      } else {
        let count = 0
        for (let index = 0; index < row.permissions.length; index++) {
          const element = row.permissions[index];
          if (element.selected) {
            count++
          }
        }
        row.selected = (count == row.permissions.length)
      }
    },
    // 行右键批量处理
    rowRightClick (row, column, event) {
      if (this.roleCode == 'admin') {
        return
      }
      //获取当前选中的个数
      let count = 0
      for (let index = 0; index < row.permissions.length; index++) {
        const element = row.permissions[index];
        if (element.selected) {
          count++
        }
      }
      // 选中的多就先取消选中，反之...
      let selected = true
      if (count > row.permissions.length / 2) {
        selected = false
      }
      for (let index = 0; index < row.permissions.length; index++) {
        const element = row.permissions[index];
        element.selected = selected
      }
      row.selected = selected
      // 加个提示避免看不到变化误解无操作
      // let text = `已${selected ? '选中' : '取消'}${row.name}的所有权限`
      // this.$elMessage.success(text)
    },
    // 列右键批量处理（只有表头可触发）
    headerRightClick (column, event) {
      if (this.roleCode == 'admin') {
        return
      }
      let label = column.label
      // 先找到点击列在源数据中所处下标
      let columnIndex = 0
      for (let index = 0; index < this.buttons.length; index++) {
        const element = this.buttons[index];
        if (element.description === label) {
          columnIndex = index - 1 //buttons内首个元素不在有效下标范围
          break
        }
      }
      if (columnIndex < 0) return
      //获取当前选中的个数
      let count = 0
      for (let index = 0; index < this.rightDataList.length; index++) {
        const element = this.rightDataList[index];
        let item = element.permissions[columnIndex]
        if (item.selected) {
          count++
        }
      }
      // 选中的多就先取消选中，反之...
      let selected = true
      if (count > this.rightDataList.length / 2) {
        selected = false
      }
      for (let index = 0; index < this.rightDataList.length; index++) {
        const element = this.rightDataList[index];
        let item = element.permissions[columnIndex]
        item.selected = selected
        if (selected) {
          let rowCount = 0
          for (let i = 0; i < element.permissions.length; i++) {
            const ele = element.permissions[i];
            if (ele.selected) {
              rowCount++
            }
          }
          element.selected = rowCount == element.permissions.length
        } else {
          element.selected = false
        }
      }

      // 加个提示避免看不到变化误解无操作
      // 快速选中时提示比较烦人，固移除提示
      // let text = `已${selected ? '选中' : '取消'}所有的${label}权限`
      // this.$elMessage.success(text)
    }
  },
}
</script>

<style scoped lang='scss'>
.asideTable {
  height: 100%;
  width: 100%;
  display: flex;
}

.all {
  // width: 2.250141rem;
  // width: auto;
  // float: left;
  min-width: 110px;
  width: 185px;
  height: 100%;
  border: 1px solid #e3e3e3;
  border-right: none;
  position: relative;

  .alltitle {
    width: 100%;
    height: 31px;
    line-height: 31px;
    text-align: center;
    position: absolute;
    top: 0;
    z-index: 999;
    color: #666666;
    font-size: 12px;
    background-color: #ededed;
  }

  .tree_div {
    width: 100%;
    margin-top: 31px;
    height: calc(100% - 31px);
    overflow-y: scroll;
  }
}

.table_module {
  width: calc(100% - 185px);
  height: 100%;
}

// 隐藏滚动条
::-webkit-scrollbar {
  width: 0 !important;
}

::-webkit-scrollbar {
  width: 0 !important;
  height: 0;
}

.warningTxt {
  font-size: 0.225014rem;
  color: #666666;
  line-height: 0.375023rem;
  padding-left: 0.187512rem;
}

::v-deep .el-tree-node__content {
  // padding-left: 0 !important;
  padding-right: 6px;
}

::v-deep .el-tree-node__label {
  font-size: 13px;
}
</style>


